﻿using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Web;
using HiTeachers.Entities;
using HiTeachers.Utilities;

namespace HiTeachers.Web.Payment
{
    public class NlCheckout
    {
        private const string NganluongUrl = "https://www.nganluong.vn/checkout.php";
        private const string MerchantSiteCode = "21228";	//thay mã merchant site mà bạn dã dang ký vào dây
        public const string SecurePass = "gnouhp!12nglg";	//thay mật khẩu giao tiếp giữa website của bạn với NgânLượng.vn mà bạn dã dang ký vào dây
        public static string Receiver = "nganluong@hiteachers.com";//Tài khoản nhận tiền 

        public static String BuildCheckoutUrl(string return_url, string receiver, string transaction_info, string order_code, string price)
        {
            // Tạo biến secure code
            string secureCode = "";

            secureCode += MerchantSiteCode;

            secureCode += " " + HttpUtility.UrlEncode(return_url).ToLower();

            secureCode += " " + receiver;

            secureCode += " " + transaction_info;

            secureCode += " " + order_code;

            secureCode += " " + price;

            secureCode += " " + SecurePass;

            // Tạo mảng bam
            var ht = new Hashtable();

            ht.Add("merchant_site_code", MerchantSiteCode);

            ht.Add("return_url", HttpUtility.UrlEncode(return_url).ToLower());

            ht.Add("receiver", receiver);

            ht.Add("transaction_info", transaction_info);

            ht.Add("order_code", order_code);

            ht.Add("price", price);

            ht.Add("secure_code", GetMd5Hash(secureCode));

            // Tạo url redirect
            string redirectUrl = NganluongUrl;

            if (redirectUrl.IndexOf("?") == -1)
            {
                redirectUrl += "?";
            }
            else if (redirectUrl.Substring(redirectUrl.Length - 1, 1) != "?" && redirectUrl.IndexOf("&") == -1)
            {
                redirectUrl += "&";
            }

            string url = "";

            // Duyệt các phần tử trong mảng bam ht1 d? t?o redirect url
            IDictionaryEnumerator en = ht.GetEnumerator();

            while (en.MoveNext())
            {
                if (url == "")
                    url += en.Key.ToString() + "=" + en.Value.ToString();
                else
                    url += "&" + en.Key.ToString() + "=" + en.Value.ToString();
            }

            string rdu = redirectUrl + url;

            return rdu;
        }

        public static Boolean VerifyPaymentUrl(string transaction_info, string order_code, string price, string payment_id,
            string payment_type, string error_text, string secure_code)
        {
            // Tạo mã xác thực cho web
            string str = "";

            str += " " + transaction_info;

            str += " " + order_code;

            str += " " + price;

            str += " " + payment_id;

            str += " " + payment_type;

            str += " " + error_text;

            str += " " + MerchantSiteCode;

            str += " " + SecurePass;

            // Mã hóa các tham s?
            string verifySecureCode = "";

            verifySecureCode = GetMd5Hash(str);

            // Xác th?c mã c?a ch? web v?i mã tr? v? t? nganluong.vn
            if (verifySecureCode == secure_code) return true;

            return false;
        }

        public static void SendNotityPaymentEmail(Teacher teacher, string paiedFees, DateTime paiedDate)
        {
            string tmpPath = HttpContext.Current.Server.MapPath("/mailtemplates");
            string mailCntPath = Path.Combine(tmpPath, "MailContents.xml");

            var dataSet = new DataSet();
            dataSet.ReadXml(mailCntPath);
            DataRow[] rows = dataSet.Tables["MemberPayment"].Select();
            string subject = Convert.ToString(rows[0]["Subject"]);

            NVelocityBuilder.SetResourcePath(tmpPath);
            var contentMail = NVelocityBuilder.PaymentEmailBuider(Convert.ToString(rows[0]["Content"]), teacher.Name, teacher.Email,
                CryptorEngine.Decrypt(teacher.Password, CryptorEngine.EncryptKey, true), teacher.ActivatedDate, teacher.DeactivatedDate, paiedFees,
                paiedDate);

            EmailSender.SendMail(subject, contentMail, teacher.Email);
        }

        #region Private Methods
        private static string GetMd5Hash(string input)
        {
            var x = new System.Security.Cryptography.MD5CryptoServiceProvider();

            byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);

            bs = x.ComputeHash(bs);

            var s = new System.Text.StringBuilder();

            foreach (byte b in bs) s.Append(b.ToString("x2").ToLower());

            String md5String = s.ToString();

            return md5String;
        }
        #endregion
    }
}
